const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  // 代理 /caipiao 路径到极速数据API
  app.use(
    '/caipiao',
    createProxyMiddleware({
      target: 'https://api.jisuapi.com/caipiao',
      changeOrigin: true,
      secure: true,
      logLevel: 'debug',
      pathRewrite: {
        '^/caipiao': '' // 移除 /caipiao 前缀，因为target已经包含了/caipiao
      },
      onProxyReq: (proxyReq, req, res) => {
        console.log('代理请求:', req.method, req.url, '-> https://api.jisuapi.com' + req.url);
        // 确保请求头正确设置
        proxyReq.setHeader('Accept', 'application/json');
        proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
        proxyReq.setHeader('Referer', 'https://api.jisuapi.com');
      },
      onProxyRes: (proxyRes, req, res) => {
        console.log('代理响应:', proxyRes.statusCode, proxyRes.headers['content-type'], req.url);
        // 设置CORS头
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
      },
      onError: (err, req, res) => {
        console.error('代理错误:', err.message, req.url);
        if (!res.headersSent) {
          res.status(500).json({ error: '代理请求失败', message: err.message });
        }
      }
    })
  );
  
  // 添加通用API代理，处理其他可能的API路径
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'https://api.jisuapi.com',
      changeOrigin: true,
      secure: true,
      logLevel: 'debug',
      pathRewrite: {
        '^/api': '' // 移除 /api 前缀
      },
      onProxyReq: (proxyReq, req, res) => {
        console.log('通用API代理请求:', req.method, req.url, '-> https://api.jisuapi.com' + req.url.replace('/api', ''));
        proxyReq.setHeader('Accept', 'application/json');
        proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
        proxyReq.setHeader('Referer', 'https://api.jisuapi.com');
      },
      onProxyRes: (proxyRes, req, res) => {
        console.log('通用API代理响应:', proxyRes.statusCode, proxyRes.headers['content-type'], req.url);
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
      },
      onError: (err, req, res) => {
        console.error('通用API代理错误:', err.message, req.url);
        if (!res.headersSent) {
          res.status(500).json({ error: 'API代理请求失败', message: err.message });
        }
      }
    })
  );
};